package com.xhlj.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhlj.entity.UserInfo;
import com.xhlj.mapper.UserInfoMapper;
import com.xhlj.service.UserInfoService;
import com.xhlj.service.impl.LoginService;
import com.xhlj.utils.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("weixin")
public class WeixinController {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private JwtHelper helper;
    @Resource
    private UserInfoMapper userInfoMapper;

    /*
     * 集成微信登录
     * 1. 获取登录验证码(前端)
     * @param:tempUserid:  String 临时用户凭证
     *    内部我们向易登获取二维码 getWeixinUrl
     * 秘钥:a4f2c83f
     * @return: 二维码url+tempUserid;
     *
     * */
    @GetMapping("/qrcode")
    public Map getWeixinQRcode() {
        String result = restTemplate.getForObject(String.format("https://yd.jylt.cc/api/wxLogin/tempUserId?secret=%s", "a4f2c83f"), String.class);
        Map map = JSONObject.parseObject(result, Map.class);
        int code = (int) map.get("code");
        if (code == 0) {
            Map data = (Map) map.get("data");
            stringRedisTemplate.opsForValue().set(RedisKey.Weixin_Login_key + (String) data.get("tempUserId"), (String) data.get("tempUserId"));
        }
        return map;
    }

    /*
     * 接受易登的返回的登录信息二维码URL
     * http://62e6f69a.r6.cpolar.top/weixin/receive
     * */
    @PostMapping("receive")
    public Map receiveWeixinUrl(@RequestBody String body, HttpServletRequest request) {
        Map<String,Object> data = JSONObject.parseObject(body, Map.class);
        //TODO:微信扫码回调
        //请求参数说明:
        //“scanSuccess”: true,扫码成功；false,扫码失败
        //“tempUserId”: 用户临时标识
        if (data.containsKey("scanSuccess") && (Boolean) data.get("scanSuccess")) {
            System.out.println("扫码成功");
        }
        if (data.containsKey("scanSuccess") && ! (Boolean) data.get("scanSuccess")) {
            System.out.println("扫码失败");
        }
        //TODO:用户取消授权回调
        // 请求参数说明
        //“cancelLogin”: true,用户拒绝授权，登录不成功
        //“tempUserId”: 用户临时标识
        if (data.containsKey("cancelLogin")) {
            System.out.println("取消登录");
        }
        if (data.get("tempUserId") != null && data.containsKey("wxMaUserInfo")) {

            String tempUserId = data.get("tempUserId").toString();
            System.out.println("tempUserId = " + tempUserId);
            Map<String, Object> userinfo = (Map<String, Object>) data.get("wxMaUserInfo");
            String openid = userinfo.get("openId").toString();      //微信用户唯一标识-28位
            String gender = userinfo.get("gender").toString();      //用户性别
            String avatarUrl = userinfo.get("avatarUrl").toString(); //头像地址
            String nickname = userinfo.get("nickName").toString();  //用户昵称

            UserInfo info = new UserInfo();
            info.setUserPhone(openid);
            info.setUserType(UserType.ONLINE.getValue());
            info.setUserNickName(nickname);
            info.setUserPoints(0);
            info.setUserPassword("");
            LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserInfo::getUserPhone, openid);

            UserInfo userInfo = userInfoService.getOne(wrapper);
            if (userInfo == null) {
                userInfoMapper.insert(info);
            }
            PayLoad payLoad = new PayLoad(openid, UserType.ONLINE, userInfo.getUserId() == null ? info.getUserId() : userInfo.getUserId());
            String token = helper.createToken(payLoad);
            /*把那个值改成真正的账号*/
            stringRedisTemplate.opsForValue().set(RedisKey.Weixin_Login_key + tempUserId, openid);
            String key = JSON.toJSONString(payLoad).replaceAll(":", "@");
            stringRedisTemplate.opsForValue().set(RedisKey.Login_token_prefix + key, token);
            /*这边还没有真正登录,前台需要用tempUserId,来获取已经生成的Token*/

            System.out.println("userinfo = " + userinfo);

        }
        Map result = new HashMap();
        result.put("code", "0");
        result.put("msg", "无");
        return result;
    }

    @GetMapping("/token")
    public Result getWeixinToken(String tempUserId) {
        String key = RedisKey.Weixin_Login_key + tempUserId;
        String token = null;
        if (stringRedisTemplate.hasKey(key) && !tempUserId.equals(stringRedisTemplate.opsForValue().get(key))) {
            String openid = stringRedisTemplate.opsForValue().get(key);
            stringRedisTemplate.delete(key);

            LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserInfo::getUserPhone, openid);
            UserInfo userInfo = userInfoService.getOne(wrapper);
            PayLoad payLoad = new PayLoad(openid, UserType.fromValue(userInfo.getUserType()), userInfo.getUserId());
            String tokenKey = JSON.toJSONString(payLoad).replaceAll(":", "@");
            System.out.println("tokenKey = " + tokenKey);
            token = stringRedisTemplate.opsForValue().get(RedisKey.Login_token_prefix + tokenKey);
            return Result.ok(token);
        } else {
            return Result.build(null, 400, "验证码即将过期,等待用户扫码获取微信用户信息中");
        }

    }

}
